(function ($) {
    "use strict";

    var prioritySlider = createSlider({ min:1, max:10, defaultValue:5, popover:true, background:'linear-gradient(to right, #5bc0de 0%, #5d5386 50%, #e23f83 100%)'});
    $('.priority_slider').append(prioritySlider);
    $(".necessary").each(function () {
        $(this).append($('<span style="color:red;">&nbsp;*</span>'));
    });
    loadInputEmbedCloseBtns();
    var task_type_native = $('.task-type-native');
    var task_type_remote = $('.task-type-remote');
    var task_type_mq = $('.task-type-mq');
    var task_cycle_fire = $('.task-cycle-fire');
    var fire_time_label = $('#fireTimeLabel');
    var first_fire_time_label = $('#firstFireTimeLabel');
    var nextFireTimeInput = $('input[name="nextFireTime"]');
    var task_cycle_cron = $('.task-cycle-cron');
    var error_policy_retry = $('.error-policy-retry');
    var whiteList = $('.whiteList');
    var blackList = $('.blackList');
    var readonly_invalid_feedback_mqConfigId = $('.readonly-invalid-feedback.mqConfigId');
    var readonly_invalid_feedback_nexFireTime = $('.readonly-invalid-feedback.nexFireTime');
    var mqConfigIdInput = $('input[name="mqConfigId"]');
    var doubleBoxArray = [];
    $('.doublebox').each(function(){doubleBoxArray.push($(this))});
    fire_time_label.detach();
    readonly_invalid_feedback_nexFireTime.detach();
    task_type_remote.detach();
    task_type_mq.detach();
    whiteList.detach();
    blackList.detach();
    page.bindTaskType = function () {
        var checkTaskType = function () {
            var taskType = $('.task-type');
            var taskTypeChecked = $('input[type=radio][name="taskType"]:checked');
            var taskTypeVal = taskTypeChecked.val();
            if (taskTypeVal == 'N') {
                task_type_remote.detach();
                task_type_mq.detach();
                taskType.after(task_type_native);
                translate(task_type_native);
            } else if (taskTypeVal == 'R') {
                task_type_native.detach();
                task_type_mq.detach();
                taskType.after(task_type_remote);
                translate(task_type_remote);
            } else {
                task_type_native.detach();
                task_type_remote.detach();
                taskType.after(task_type_mq);
                translate(task_type_mq);
            }
            resizeContentWithNiceScroll();
        };
        $('input[type=radio][name="taskType"]').each(function () {
            $(this).change(function () {
                checkTaskType();
            });
        });
    };

    page.bindTaskCycle = function () {
        var checkTaskCycle = function () {
            var taskCycle = $('.task-cycle');
            var taskCycleVal = $('input[type=radio][name="taskCycle"]:checked').val();
            if (taskCycleVal == 'R') {
                task_cycle_fire.detach();
                task_cycle_cron.detach();
            } else if (taskCycleVal == 'T') {
                task_cycle_fire.detach();
                task_cycle_cron.detach();
                first_fire_time_label.detach();
                task_cycle_fire.prepend(fire_time_label);
                nextFireTimeInput.attr('required', 'required');
                if (nextFireTimeInput.val() !== '') {
                    nextFireTimeInput.addClass("readonly-valid");
                } else {
                    nextFireTimeInput.addClass('readonly-invalid');
                    $('#fireTimeContainer').append(readonly_invalid_feedback_nexFireTime);
                }
                taskCycle.after(task_cycle_fire);
                translate(task_cycle_fire);
                page.bindFireTimeDatePick();
            } else {
                task_cycle_fire.detach();
                task_cycle_cron.detach();
                fire_time_label.detach();
                task_cycle_fire.prepend(first_fire_time_label);
                nextFireTimeInput.removeAttr('required').removeClass('readonly-invalid readonly-valid');
                readonly_invalid_feedback_nexFireTime.detach();
                taskCycle.after(task_cycle_fire);
                taskCycle.after(task_cycle_cron);
                translate(task_cycle_fire);
                translate(task_cycle_cron);
                page.bindFireTimeDatePick();
            }
            resizeContentWithNiceScroll();
        };
        $('input[type=radio][name="taskCycle"]').each(function () {
            $(this).change(function () {
                checkTaskCycle();
            });
        });
    };

    page.bindErrorPolicy = function () {
        var checkErrorPolicy = function () {
            var errorPolicy = $('.error-policy');
            var errorPolicyVal = $('input[type=radio][name="errorPolicy"]:checked').val();
            if (errorPolicyVal == 'R') {
                error_policy_retry.detach();
                errorPolicy.after(error_policy_retry);
                translate(error_policy_retry);
            } else {
                error_policy_retry.detach();
            }
            resizeContentWithNiceScroll();
        };
        $('input[type=radio][name="errorPolicy"]').each(function () {
            $(this).change(function () {
                checkErrorPolicy();
            });
        });
    };

    page.bindBlackWhiteList = function () {
        var appendBlackList = function () {
            $('.useBlackWhiteList').after(blackList);
            translate(blackList);
            bindDoubleBoxPopover($('input[name="blackList"]'), {
                name: 'serverId',
                loadUrl: "/schedule/server/getAllServerId",
                fun: {
                    beforeShow: function(){
                        whiteList.detach();
                    },
                    callBack: function (val) {
                        if (val === '') {
                            blackList.before(whiteList);
                            translate(whiteList);
                            resizeContentWithNiceScroll();
                        }
                    }
                }
            });
        };
        var appendWhiteList = function () {
            $('.useBlackWhiteList').after(whiteList);
            translate(whiteList);
            bindDoubleBoxPopover($('input[name="whiteList"]'), {
                name: 'serverId',
                loadUrl: "/schedule/server/getAllServerId",
                fun: {
                    beforeShow: function() {
                        blackList.detach();
                    },
                    callBack: function (val) {
                        if (val === '') {
                            whiteList.after(blackList);
                            translate(blackList);
                            resizeContentWithNiceScroll();
                        }
                    }
                }
            });
        };
        var checkBlackWhiteList = function ($this) {
            var checked = $this[0].checked;
            if (checked) {
                var whiteListValue = whiteList.find('input[name="whiteList"]').data('value');
                var blackListValue = blackList.find('input[name="blackList"]').data('value');
                if ((blackListValue === undefined || blackListValue === '') && (whiteListValue === undefined || whiteListValue === '')) {
                    appendBlackList();
                    appendWhiteList();
                } else if (blackListValue !== undefined && blackListValue !== '' && whiteListValue !== undefined && whiteListValue !== '') {
                    appendWhiteList();
                } else {
                    if (blackListValue !== undefined && blackListValue !== '') {
                        appendBlackList();
                    } else {
                        appendWhiteList();
                    }
                }
            } else {
                whiteList.detach();
                blackList.detach();
            }
            resizeContentWithNiceScroll();
        };
        $('#blackWhiteList').on('change', function(){
            checkBlackWhiteList($(this));
        });
    };

    page.bindFireTimeDatePick = function () {
        var dateRangePicker = $('.daterangepicker');
        if (dateRangePicker) {
            dateRangePicker.remove();
        }
        nextFireTimeInput.daterangepicker({
            singleDatePicker: true,
            autoApply: false,
            autoUpdateInput: false,
            timePicker24Hour: true,
            timePickerSeconds: true,
            timePicker: true,
            "locale": {
                format: 'YYYY-MM-DD HH:mm:ss'
            },
            "minDate": moment()
        }).on('apply.daterangepicker', function (ev, picker) {
            picker.element.val(picker.startDate.format(picker.locale.format));
            if ($('input[type=radio][name="taskCycle"]:checked').val() === 'T') {
                picker.element.removeClass("readonly-invalid").addClass("readonly-valid");
                readonly_invalid_feedback_nexFireTime.detach();
            }
        }).on('beforeShow.daterangepicker', function (ev, picker) {
            picker.startDate = picker.minDate = moment();
        }).on('show.daterangepicker', function () {
            nextFireTimeInput.addClass('focus');
        }).on('hide.daterangepicker', function () {
            nextFireTimeInput.removeClass('focus');
        });
    };

    page.bindTaskSwitch = function () {
        var checkTaskSwitch = function () {
            var taskSwitchBtn = $('.task-switch-btn');
            if (taskSwitchBtn.hasClass("switch-checked")) {
                taskSwitchBtn.removeClass('switch-checked').find('span').attr('translateValue', 'C').text(getTranslateValueByFor('taskSwitch.C'));
                $('input[name="taskSwitch"]').val('C');
            } else {
                taskSwitchBtn.addClass('switch-checked').find('span').attr('translateValue', 'O').text(getTranslateValueByFor('taskSwitch.O'));
                $('input[name="taskSwitch"]').val('O');
            }
        };
        checkTaskSwitch();
        $('.task-switch-btn').on('click', function () {
            checkTaskSwitch();
        });
    };

    page.bindTaskType();
    page.bindTaskCycle();
    page.bindErrorPolicy();
    page.bindBlackWhiteList();
    page.bindFireTimeDatePick();
    page.bindTaskSwitch();
    bindDoubleBoxPopover(mqConfigIdInput, {name:'mqConfigId', direction:'bottom',loadUrl:"/schedule/mq/getAllMqConfigId"});
    bindDoubleBoxPopover($('input[name="dependentTaskId"]'), {name:'taskId', direction:'bottom',loadUrl:"/schedule/task/getAllTaskId"});

    Array.prototype.filter.call(document.getElementsByClassName('needs-validation'), function (form) {
        $(form).find('#submitForm').on('click', function (event) {
            if (form.checkValidity() === false) {
                event.preventDefault();
                event.stopPropagation();
            } else {
                submitForm();
            }
            form.classList.add('was-validated');
        });
        $(form).find('#resetForm').on('click', function (event) {
            event.preventDefault();
            $(form).find('input[type="text"]').each(function(){$(this).val('')});
            hideInputEmbedCloseBtns($(form));
            for (var i = 0, length = doubleBoxArray.length; i < length; i++) {
                doubleBoxArray[i].data('value', '').data('doubleBox') && doubleBoxArray[i].data('doubleBox').elements.removeAllButton.click();
                removeTitle(doubleBoxArray[i]);
            }
            $('#blackWhiteList')[0].checked && $('#blackWhiteListClick').click();
            form.classList.remove('was-validated');
            readonly_invalid_feedback_mqConfigId.detach();
            readonly_invalid_feedback_nexFireTime.detach();
            mqConfigIdInput.addClass("readonly-invalid").removeClass("readonly-valid").after(readonly_invalid_feedback_mqConfigId);
            $('input[type=radio][name="taskCycle"]:checked').val() === 'T' && nextFireTimeInput.addClass("readonly-invalid").removeClass("readonly-valid").next().after(readonly_invalid_feedback_nexFireTime);
        });
    });

    function submitForm() {
        var taskId = $('input[name="taskId"]').val();
        var data = {
            'taskId':taskId,
            'taskName':$('input[name="taskName"]').val(),
            'taskType':$('input[name="taskType"]:checked').val(),
            'beanId':$('input[name="beanId"]').val(),
            'beanClass':$('input[name="beanClass"]').val(),
            'remoteUrl':$('input[name="remoteUrl"]').val(),
            'mqConfigId':mqConfigIdInput.data('value'),
            'mqDestination':$('input[name="mqDestination"]').val(),
            'mqCallback':$('input[name="mqCallback"]').val(),
            'priority':prioritySlider.data('sliderValue'),
            'partitionCount':$('input[name="partitionCount"]').val(),
            'partitionMode':$('input[name="partitionMode"]:checked').val(),
            'cronExpression':$('input[name="cronExpression"]').val(),
            'nextFireTime':nextFireTimeInput.val(),
            'dependentTaskId':$('input[name="dependentTaskId"]').data('value'),
            'dependencePolicy':$('input[name="dependencePolicy"]:checked').val(),
            'blockPolicy':$('input[name="blockPolicy"]:checked').val(),
            'errorPolicy':$('input[name="errorPolicy"]:checked').val(),
            'retryCount':$('input[name="retryCount"]').val(),
            'retryInterval':$('input[name="retryInterval"]').val(),
            'retryPolicy':$('input[name="retryPolicy"]:checked').val(),
            'parameters':$('input[name="parameters"]').val(),
            'alarm':$('input[name="alarm"]')[0].checked ? 'Y' : 'N',
            'taskSwitch':$('input[name="taskSwitch"]').val()
        };
        var useWhiteBlackList = $('input[name="useWhiteBlackList"]')[0].checked ? 'Y' : 'N';
        if (useWhiteBlackList === 'Y') {
            data['whiteList'] = $('input[name="whiteList"]').data('value');
            data['blackList'] = $('input[name="blackList"]').data('value');
        }
        data['useWhiteBlackList'] = useWhiteBlackList;
        axiosPost({
            url : '/schedule/task/addTask',
            data : data,
            success : function(result) {
                if ('fail' === result.status) {
                    showErrorNoty({
                        timeout: 5000,
                        translateFor: 'message.' + result.msgCode
                    });
                } else {
                    newSuccessModal({
                        content: "modal.addTaskSuccess",
                        okFun: function () {
                            redirect('taskDetail', taskId);
                        }
                    });
                }
            }
        });
    }
})(jQuery);